package com.seezoon.infrastructure.rpc.jt808;

import com.seezoon.infrastructure.error.ErrorCode;
import com.seezoon.infrastructure.exception.ExceptionFactory;
import com.seezoon.infrastructure.rpc.jt808.dto.JtResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestClient;

/**
 * 调用JT808 server 发送指令
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Validated
public class SendCommandService {

    public final static String COMMAND_SOUND_RECORDING = "sound_recording";
    private final RestClient restClient;

    public <T> T execute(String endpoint, @NotEmpty String command, @NotNull Object requestBody,
            @NotEmpty String serialNo) {
        if (StringUtils.isEmpty(endpoint)) {
            log.error("JT808 end faild endpoint is empty , serialNo:{}, body={},", serialNo);
            throw ExceptionFactory.bizException(ErrorCode.DEVICE_SEND_MSG_FAILED);
        }
        String url = "http://" + endpoint + "/" + command;
        try {
            log.info("Send command for device: {},requestBody:{}", serialNo, requestBody);
            JtResponse<T> response = restClient.post()
                    .uri(url)
                    .contentType(MediaType.APPLICATION_JSON)
                    .header("Authorization", "Bearer " + serialNo)
                    .body(requestBody)
                    .retrieve()
                    .body(new ParameterizedTypeReference<JtResponse<T>>() {
                    });
            if (response.isSuccess()) {
                log.error("JT808 end faild, serialNo:{},url={}, body={}, code:{},msg:{}", serialNo, url,
                        requestBody, response.getCode(), response.getMsg());
                throw ExceptionFactory.bizException(ErrorCode.DEVICE_SEND_MSG_FAILED);
            }
            return response.getData();
        } catch (Exception e) {
            log.error("JT808 end faild, serialNo:{},url={}, body={}, error={}", serialNo, url,
                    requestBody,
                    e.getMessage(), e);
            throw ExceptionFactory.bizException(ErrorCode.DEVICE_SEND_MSG_FAILED);
        }
    }
}
